package com.face.pass.active.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.face.pass.active.App;
import com.face.pass.active.dao.UserDao;
import com.face.pass.active.model.User;
import com.face.pass.active.view.LoginView;
import com.face.pass.active.view.MainView;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.google.common.hash.Hashing;

import de.felixroske.jfxsupport.FXMLController;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

@FXMLController
public class LoginController{
	private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);
	@FXML
	TextField tfUserName;
	@FXML
	PasswordField tfPassword;
	@FXML
	Label tfMessage;
	@FXML
	Button btnLogin;
	
	@Autowired
	private LoginView loginView;
	
	@Autowired
	private UserDao userDao;

	@FXML
	public void onLogin(final Event e) {
		//判断登录密码是否正确，如果正确则允许登录
		String userName = tfUserName.getText();
		String password = tfPassword.getText();
		if(Strings.isNullOrEmpty(userName)||Strings.isNullOrEmpty(password)) {
			tfMessage.setText("用户名或者密码为空");
			return;
		}
		String hashPassword = Hashing.md5().newHasher().putString(password, Charsets.UTF_8).hash().toString();
		User user = userDao.findByName(userName);
		if(user == null || !user.getPassword().equals(hashPassword)) {
			tfMessage.setText("用户名或者密码错误");
			return;
		}
		LOG.debug(String.format("userName: %s password: %s",userName,password));
		App.showView(MainView.class);
		loginView.getView().setDisable(false);
	}
	
	@FXML
	private void onKeyPressed(final KeyEvent e) {
		if(e.getCode() == KeyCode.ENTER) {
			btnLogin.fire();
		}
	}

}
